package leetcode.algorithm.dynamicPlan;

import java.util.*;

public class TenElevn {

    List<int[]> list = new ArrayList<>();
    // Boolean[] flag;
    public static void main(String[] args) {
        int[][] intervals = {{2,3},{4,5},{6,7},{8,9},{1,10}};
        Map<Integer,int[]> map = new HashMap<>();
        Arrays.sort(intervals, new Comparator<int[]>() {
            public int compare(int[] interval1, int[] interval2) {
                return interval1[0] - interval2[0];
            }
        });
        for(int i=0;i<intervals.length;i++){
            System.out.println(Arrays.toString(intervals[i]));
        }




/*        TenElevn t = new TenElevn();
        int[][] res = t.merge(intervals);
        String[] ss = new String[res.length];
        for(int i=0;i<res.length;i++) {
            ss[i] = (Arrays.toString(res[i]));
            System.out.println(ss[i]);
        }*/
    }


    public int[][] merge(int[][] intervals) {
        int len = intervals.length;
        Boolean[] flag = new Boolean[len];
        for(int i=0;i<len;i++)flag[i]=false;

        for(int i=0;i<len;i++){
            for(int j=i+1;j<len;j++){
                if(flag[j]==true)continue;
                if(flag[i]==false&&flag[j]==false)interval(intervals[i], intervals[j], flag, j, i);
            }
            System.out.println(Arrays.toString(flag));
        }

        for(int i=0;i<len;i++){
            if(flag[i]==false)list.add(intervals[i]);
        }

        int[][] res = new int[list.size()][2];
        for(int i=0;i<list.size();i++){
            res[i]=list.get(i);
        }
        return res;

    }

    //这里的是指向对象;所以cur指向的实际上就是start的地址
    public void interval(int[] cur, int[] nex, Boolean[] flag, int j, int i ){

        if((cur[0]>=nex[0]&&cur[0]<=nex[1])
                ||(cur[1]>=nex[0]&&cur[1]<=nex[1])
                ||(nex[0]>=cur[0]&&nex[0]<=cur[1])
                ||(nex[1]>=cur[0]&&nex[1]<=cur[1])){
            cur[0]=Math.min(cur[0],nex[0]);
            cur[1]=Math.max(cur[1],nex[1]);
            flag[j]=true;
        }

        if(j==flag.length-1) {
            list.add(cur);
            flag[i]=true;
        }
    }
}

